<?php
/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace builder\helper;

use Yii;
use yii\helpers\Html;
use yii\helpers\StringHelper;

/**
 * 字符串
 * @author cleverstone
 * @since ym2.0
 */
class Str extends StringHelper
{
    /**
     * 随机字符串
     * @param int $len 字符串长度，最小1，最大32
     * @param bool $trimSpecial 是否去除特殊字符，如：-_
     * @return string
     * @throws \yii\base\Exception
     */
    public static function random($len = 32, $trimSpecial = false)
    {
        if ($len < 1 || $len > 255) {
            $len = 32;
        }

        $randomStr = Yii::$app->security->generateRandomString($len);
        if ($trimSpecial === true) {
            return strtr($randomStr, ['-' => rand(0, 9), '_' => rand(0, 9)]);
        }

        return $randomStr;
    }

    /**
     * 生成长度为64的唯一字符
     * @return string
     * @throws \Random\RandomException
     */
    public static function uniqueRandom(): string
    {
        return hash_hmac('sha256', Num::order(), bin2hex(random_bytes(14)));
    }

    /**
     * 高亮字符串
     * @param string $str 字符串
     * @return null|string|string[]
     */
    public static function highlight($str)
    {
        $result = highlight_string("<?php\n" . $str, true);
        return preg_replace('/&lt;\\?php<br \\/>/', '', $result, 1) ?: $str;
    }

    /**
     * 转义JS冲突文本
     * @param string $text 文本内容
     * @return string
     */
    public static function escapeCRLF($text)
    {
        return strtr($text, [
            "\r" => "\\r",
            "\n" => "\\n",
            '"' => '\"',
            "'" => "\'",
        ]);
    }

    /**
     * 字符串超出尾部省略
     * @param string $str 内容字符串
     * @param int $baseLength 基准长度
     * @param boolean $htmlEncode 是否进行HTML编码
     * @param boolean $hoverShowContent hover显示完整内容
     * @param string $ellipsisSymbol 省略符号
     * @param array $options 根元素选项
     * @return string
     */
    public static function overflowEllipsis($str, $baseLength = 30, $htmlEncode = false, $hoverShowContent = false, $ellipsisSymbol = '...', $options = [])
    {
        if ($baseLength <= 0 || !is_int($baseLength)) { throw new \InvalidArgumentException('参数baseLength必须是大于0的整数.');}
        $result = static::truncate($str, $baseLength, $ellipsisSymbol);
        if ($hoverShowContent) {
            Html::addCssClass($options, ['layout' => 'lh-1-5 d-inline-block']);
            if ($result !== $str) {
                $options = array_merge($options, [
                    'data-toggle' => 'popover',
                    'data-trigger' => 'hover',
                    'data-html' => 'true',
                    'data-content' => Html::encode($str),
                    'data-custom-class' => 'f12 white-space-pre-wrap pointer-event-none',
                    'ym2-bootstrap-plugin' => 'popover',
                ]);

            }
            return H5::text($htmlEncode ? Html::encode($result) : $result, $options, 'div');
        }

        return $htmlEncode ? Html::encode($result) : $result;
    }

    /**
     * 字符串超出中间省略
     * @param string $str
     * @param int $baseLength
     * @param string $ellipsisSymbol
     * @return string
     */
    public static function overflowMiddleEllipsis($str, $baseLength = 10, $ellipsisSymbol = '***')
    {
        if ($baseLength < 2 || !is_int($baseLength)) {
            throw new \InvalidArgumentException('基准长度必须是大于2的整数~');
        }

        if (mb_strlen($str, '8bit') <= $baseLength) {
            return $str;
        }

        $sliceLength = intval($baseLength / 2);
        $front = mb_substr($str, 0, $sliceLength, '8bit');
        $end = mb_substr($str, -$sliceLength, null, '8bit');

        return $front . $ellipsisSymbol . $end;
    }
}